//
//  OAuthViewController.swift
//  DSWeibo
//
//  Created by liuzhu on 2018/11/13.
//  Copyright © 2018 liuzhu. All rights reserved.
//

import UIKit
import SVProgressHUD
class OAuthViewController: UIViewController {

    let WB_App_Key = "888486566"
    let WB_App_Secret = "bc21e66a2bed2cc51725b73bf948d97b"
    let WB_Redirect_Url = "http://www.hellomeng.com"
    override func loadView() {
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //初始化导航条
        navigationItem.title = "辽宁号航空母舰"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItem.Style.plain, target: self, action: #selector(close))
        
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_App_Key)&redirect_uri=\(WB_Redirect_Url)"
        let url = URL(string: urlStr)
        let request = URLRequest(url: url!)
        webView.loadRequest(request)
    }
    
    private lazy var webView:UIWebView = {
        let wv = UIWebView()
        wv.delegate = self
        return wv
    }()
    
    @objc private func close(){
        dismiss(animated: true, completion: nil)
    }
}

extension OAuthViewController:UIWebViewDelegate{
    
    //返回true，正常加载，返回false，不加载
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool{
        //判断是否是授权回调页
        let urlStr = request.url!.absoluteString
        if !urlStr.hasPrefix(WB_Redirect_Url){
            return true
        }
        let codeStr = "code="
        if request.url!.query!.hasPrefix(codeStr){
            //授权成功,取出token
           let code = request.url!.query?.substring(from: codeStr.endIndex)
            loadAccessToken(code:code!)
        }else{
            //取消授权
            close()
        }
        return false
    }
    
    private func loadAccessToken(code:String){
        let path = "oauth2/access_token"
        let params = ["client_id":WB_App_Key,"client_secret":WB_App_Secret,"grant_type":"authorization_code","code":code,"redirect_uri":WB_Redirect_Url]
        
        NetWorkTools.shareNetworkTools().post(path, parameters: params, success: { (_, JSON) in
            let account = UserAccount.init(dict: JSON as! [String : AnyObject])
            //获取用户信息
           // account.loadUserInfo()
            account.loadUserInfo(finished: { (account, error) in
                if account != nil {
                   account?.saveAccount()
                   SVProgressHUD.showInfo(withStatus: "登录成功")
                   NotificationCenter.default.post(name: NSNotification.Name(rawValue: XMGSwitchRootViewControllerKey), object: false)
                }
                else{
                     SVProgressHUD.showInfo(withStatus: "登录失败")
                }
            })
            
        }) { (_, error) in
            print(error)
        }
    }
    
}
